package RMI.adminTOrtdg.impl;

import host.impl.Host;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import manager.impl.ServiceManager;

import properties.PropertyManager;

import enums.AdminRequestType;

import RMI.adminTOrtdg.informations.SenderInformations;
import RMI.adminTOrtdg.NetworkService;

public class Sender {
	
	private SenderInformations informations;

	public SenderInformations getInformations() {
		return informations;
	}

	public void setInformations(SenderInformations informations) {
		this.informations = informations;
	}


	public int send(AdminRequestType requestType, String ipAddress, Integer registryPortNumber) throws RemoteException {
		ServiceManager.printLog(PropertyManager.properties.getProperty("rmiSend"));
		InetAddress localIp = null;
		
		try {
			localIp = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			ServiceManager.printLog(PropertyManager.properties.getProperty("rmiAddressError"));
			e.printStackTrace();
			System.exit(0);
		}
		RMIComServerObject rmiComServerObject = 
				new RMIComServerObject(new Host(localIp.getHostAddress(),informations.getRegistryPortNumber()));
		try {
			int clientPort = informations.getClientPortNumber();

			int registryPort = registryPortNumber;
			String registryHost = ipAddress;
			
			String networkServiceBindingName = NetworkService.RTDGNetworkServiceBindingName;

			UnicastRemoteObject.exportObject(rmiComServerObject, clientPort);
			
			Registry remoteRegistry = LocateRegistry.getRegistry(registryHost, registryPort);

			NetworkService remoteService = (NetworkService)remoteRegistry.lookup(networkServiceBindingName);
			switch (requestType) {
			case REGISTRATION_REQUEST:
				ServiceManager.printLog(PropertyManager.properties.getProperty("rmiRegistrationRequest"));
				remoteService.registrationRequest(rmiComServerObject);
				break;
			case STOP:
				ServiceManager.printLog(PropertyManager.properties.getProperty("rmiStopRequest"));
				remoteService.stop();
				break;
			case PING:
				ServiceManager.printLog(PropertyManager.properties.getProperty("rmiPing"));
				remoteService.ping();
				break;
			default:
				ServiceManager.printLog(PropertyManager.properties.getProperty("rmiRequestNotSupported"));	
				break;
			}
			return 1;
		} catch (RemoteException e) {
			ServiceManager.printLog(PropertyManager.properties.getProperty("rmiSenderRemoteException"));
			if(requestType!=AdminRequestType.PING)e.printStackTrace();
			return -1;
		} catch (NotBoundException e) {
			ServiceManager.printLog(PropertyManager.properties.getProperty("rmiSenderAlreadyBoundException"));
			if(requestType!=AdminRequestType.PING)e.printStackTrace();
			e.printStackTrace();
			return -1;
		}
	}
}

